<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>全局变量管理</h3>
          <el-button type="primary" @click="openVariableDialog()">
            <el-icon><el-icon-plus /></el-icon> 添加变量
          </el-button>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else>
        <el-table 
          :data="globalVariables" 
          style="width: 100%" 
          border
          v-if="globalVariables.length > 0"
        >
          <el-table-column prop="name" label="变量名称" />
          <el-table-column prop="type" label="变量类型">
            <template #default="{ row }">
              <el-tag>{{ getTypeText(row.type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="defaultValue" label="默认值" />
          <el-table-column prop="description" label="描述" show-overflow-tooltip />
          <el-table-column label="使用此变量的事件" width="300">
            <template #default="{ row }">
              <div v-if="loadingUsage[row.id]" class="usage-loading">
                <el-skeleton :rows="1" animated />
              </div>
              <div v-else-if="variableUsage[row.id]" class="event-usage-list">
                <div v-if="variableUsage[row.id].length === 0" class="no-usage">
                  暂无事件使用此变量
                </div>
                <template v-else>
                  <div class="event-tag-list">
                    <router-link 
                      v-for="(event, index) in variableUsage[row.id].slice(0, 10)"
                      :key="event.id"
                      :to="`/events/${event.id}`"
                      class="event-link"
                    >
                      <el-tag size="small" class="event-tag">{{ event.name }}</el-tag>
                    </router-link>
                    <el-button 
                      v-if="variableUsage[row.id].length > 10" 
                      type="primary" 
                      size="small" 
                      text 
                      @click="showAllUsageEvents(row.id)"
                    >
                      更多 ({{ variableUsage[row.id].length - 10 }}+)
                    </el-button>
                  </div>
                </template>
              </div>
              <el-button v-else type="primary" size="small" text @click="loadVariableUsage(row.id)">
                查看引用
              </el-button>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="openVariableDialog(row)">
                <el-icon><el-icon-edit /></el-icon> 编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDeleteVariable(row)">
                <el-icon><el-icon-delete /></el-icon> 删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <el-empty v-else description="暂无全局变量" />
      </div>
    </el-card>
    
    <!-- 变量编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑变量' : '添加变量'"
      width="500px"
      append-to-body
    >
      <el-form 
        :model="variableForm" 
        :rules="rules" 
        ref="variableFormRef" 
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="变量名称" prop="name">
          <el-input 
            v-model="variableForm.name" 
            placeholder="变量名称，如: userId"
            :disabled="isEdit"
          />
          <div class="form-help-text">
            变量名只能包含字母、数字和下划线，且必须以字母或下划线开头
          </div>
        </el-form-item>
        
        <el-form-item label="变量类型" prop="type">
          <el-select v-model="variableForm.type" placeholder="请选择变量类型" style="width: 100%">
            <el-option label="字符串" value="string" />
            <el-option label="数字" value="number" />
            <el-option label="布尔值" value="boolean" />
            <el-option label="日期时间" value="datetime" />
            <el-option label="数组" value="array" />
            <el-option label="对象" value="object" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="默认值" prop="defaultValue">
          <el-input 
            v-model="variableForm.defaultValue" 
            placeholder="变量的默认值"
          />
          <div class="form-help-text">
            请根据变量类型设置合适的默认值，数组和对象请使用JSON格式
          </div>
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="variableForm.description" 
            type="textarea"
            rows="3"
            placeholder="变量用途描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveVariable" :loading="saveLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 所有引用事件对话框 -->
    <el-dialog
      v-model="allUsageDialogVisible"
      title="引用此变量的所有事件"
      width="700px"
      append-to-body
    >
      <div v-if="currentVariableUsage">
        <el-table 
          :data="allUsageEvents.events" 
          style="width: 100%" 
          border
          v-loading="loadingAllUsage"
        >
          <el-table-column prop="name" label="事件名称" />
          <el-table-column prop="category" label="分类" />
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <router-link :to="`/events/${row.id}`">
                <el-button type="primary" size="small">查看</el-button>
              </router-link>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="usagePagination.currentPage"
            v-model:page-size="usagePagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="allUsageEvents.total"
            @size-change="handleUsageSizeChange"
            @current-change="handleUsagePageChange"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus as ElIconPlus, Edit as ElIconEdit, Delete as ElIconDelete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const store = useStore()
const router = useRouter()

const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const saveLoading = ref(false)
const variableFormRef = ref(null)

// 获取全局变量
const globalVariables = ref([])

// 变量使用统计
const loadingUsage = ref({})
const variableUsage = computed(() => store.state.variableUsage)

// 全部引用事件对话框
const allUsageDialogVisible = ref(false)
const currentVariableId = ref(null)
const loadingAllUsage = ref(false)
const usagePagination = ref({
  currentPage: 1,
  pageSize: 10
})

// 当前选中的变量使用信息
const currentVariableUsage = computed(() => {
  if (!currentVariableId.value) return null
  return variableUsage.value[currentVariableId.value]
})

// 所有引用事件（分页）
const allUsageEvents = ref({
  events: [],
  total: 0
})

// 表单数据
const variableForm = reactive({
  name: '',
  type: 'string',
  defaultValue: '',
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入变量名称', trigger: 'blur' },
    { pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, message: '变量名只能包含字母、数字和下划线，且必须以字母或下划线开头', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择变量类型', trigger: 'change' }
  ]
}

// 获取变量类型显示文本
const getTypeText = (type) => {
  switch (type) {
    case 'string': return '字符串'
    case 'number': return '数字'
    case 'boolean': return '布尔值'
    case 'datetime': return '日期时间'
    case 'array': return '数组'
    case 'object': return '对象'
    default: return type
  }
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 加载全局变量
const loadGlobalVariables = async () => {
  loading.value = true
  try {
    const data = await store.dispatch('fetchGlobalVariables')
    globalVariables.value = data || []
  } catch (error) {
    ElMessage.error('获取全局变量失败')
  } finally {
    loading.value = false
  }
}

// 打开变量编辑对话框
const openVariableDialog = (variable = null) => {
  isEdit.value = !!variable
  
  if (variable) {
    // 编辑模式，填充表单
    Object.assign(variableForm, {
      id: variable.id,
      name: variable.name,
      type: variable.type,
      defaultValue: variable.defaultValue || '',
      description: variable.description || ''
    })
  } else {
    // 新增模式，重置表单
    Object.assign(variableForm, {
      id: null,
      name: '',
      type: 'string',
      defaultValue: '',
      description: ''
    })
  }
  
  dialogVisible.value = true
  // 在下一个 tick 重置表单校验状态
  setTimeout(() => {
    variableFormRef.value?.resetFields()
  }, 0)
}

// 保存变量
const handleSaveVariable = async () => {
  await variableFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    saveLoading.value = true
    try {
      await store.dispatch('saveGlobalVariable', variableForm)
      ElMessage.success(`${isEdit.value ? '更新' : '添加'}变量成功`)
      dialogVisible.value = false
      await loadGlobalVariables()
    } catch (error) {
      console.error(error)
      ElMessage.error(error.response?.data?.message || `${isEdit.value ? '更新' : '添加'}变量失败`)
    } finally {
      saveLoading.value = false
    }
  })
}

// 删除变量
const handleDeleteVariable = (variable) => {
  ElMessageBox.confirm(`确定要删除变量"${variable.name}"吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await store.dispatch('deleteGlobalVariable', variable.id)
      ElMessage.success('删除变量成功')
      await loadGlobalVariables()
    } catch (error) {
      ElMessage.error('删除变量失败')
    }
  }).catch(() => {})
}

// 加载变量使用情况
const loadVariableUsage = async (variableId) => {
  if (loadingUsage.value[variableId]) return
  
  loadingUsage.value[variableId] = true
  try {
    await store.dispatch('fetchVariableUsage', {
      variableId,
      variableType: 'global',
      page: 1,
      pageSize: 100 // 先获取较多数据，以便显示前10个和总数
    })
  } catch (error) {
    ElMessage.error('获取变量使用情况失败')
  } finally {
    loadingUsage.value[variableId] = false
  }
}

// 显示所有引用事件
const showAllUsageEvents = async (variableId) => {
  currentVariableId.value = variableId
  usagePagination.value.currentPage = 1
  allUsageDialogVisible.value = true
  await loadAllUsageEvents()
}

// 加载所有引用事件（分页）
const loadAllUsageEvents = async () => {
  if (!currentVariableId.value) return
  
  loadingAllUsage.value = true
  try {
    const result = await store.dispatch('fetchVariableUsage', {
      variableId: currentVariableId.value,
      variableType: 'global',
      page: usagePagination.value.currentPage,
      pageSize: usagePagination.value.pageSize
    })
    allUsageEvents.value = result
  } catch (error) {
    ElMessage.error('获取变量使用情况失败')
  } finally {
    loadingAllUsage.value = false
  }
}

// 处理分页大小变化
const handleUsageSizeChange = (size) => {
  usagePagination.value.pageSize = size
  loadAllUsageEvents()
}

// 处理页码变化
const handleUsagePageChange = (page) => {
  usagePagination.value.currentPage = page
  loadAllUsageEvents()
}

onMounted(() => {
  loadGlobalVariables()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-container {
  padding: 20px 0;
}

.form-help-text {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
  margin-top: 4px;
}

.event-usage-list {
  display: flex;
  flex-direction: column;
}

.event-tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
}

.event-link {
  text-decoration: none;
}

.event-tag {
  cursor: pointer;
}

.no-usage {
  color: #909399;
  font-size: 13px;
}

.usage-loading {
  padding: 0 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 